package com.java.project.config;

import org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.context.annotation.Bean;
import  org.springframework.context.annotation.Configuration;
import  org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import  org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import  org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import  org.springframework.security.web.SecurityFilterChain;

import javax.sql.DataSource;

@Configuration
public  class  WebSecurityConfig {
	@Bean
	public  PasswordEncoder passwordEncoder() {
		return  new  BCryptPasswordEncoder();
	}
	@Bean
	public  SecurityFilterChain securityFilterChain(HttpSecurity http) throws  Exception{
		http.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
		.mvcMatchers("/loginview","/css/**","/img/**").permitAll()
		.mvcMatchers("/book/admin/**").hasRole("ADMIN")
		.antMatchers("/public/**").permitAll()
		.anyRequest().authenticated() // 任何请求,登录后可以访问
		.and()
		.formLogin()
		.loginPage("/loginview")
		.loginProcessingUrl("/doLogin")
		.and()
		.csrf().disable()//禁止csrf 跨站请求保护;
		.headers().frameOptions().sameOrigin();
		return  http.build();
	}

	@Bean
	public UserDetailsService userDetailsService() {
		InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
		users.createUser(User.withUsername("zhangsan")
				.password("{noop}1234")
				.roles("ADMIN")
				.build());
		return  users;
	}
//
//	@Autowired
//	private DataSource dataSource;
//
//	@Bean
//	public UserDetailsService userDetailsService() {
//		String userSQL = "SELECT username,password, valid FROM user WHERE username = ?";
//		String authoritySQL = "SELECT u.username,p.authority FROM user u,priv p,user_priv up " +
//				"WHERE up.user_id=u.id AND up.priv_id=p.id AND u.username = ?";
//
//		JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource); // 通过构造器注入
//		users.setUsersByUsernameQuery(userSQL);
//		users.setAuthoritiesByUsernameQuery(authoritySQL);
//		return users;
//	}
}
